#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>


#include "AlsaOpt.h"
#include "UdpRecv.h"
#include "MyQueue.h"


void* ReadDataFromFile(void * recvListParam)
{
    AudioRecvAllSt *recvStObj = static_cast<AudioRecvAllSt*>(recvListParam);

    const char *filename = "received_file.txt";
    FILE *file = fopen(filename, "rb");
    if (file == NULL) {
        printf("Failed to open file: %s\n", filename);
        return NULL; 
    }

    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    printf("File size: %ld bytes\n", fileSize);

    int testIndex = 1;
    AudioRecvItemSt item;
    while (ftell(file) < fileSize) 
    {
        item.buffLen = fread(item.buff, 1, RECV_BUFF_SIZE, file);
        if (item.buffLen > 0) 
        {
            // if (testIndex % 500 == 0)
            // {
            //     printf("testIndex = %d, Read %d bytes from file\n", testIndex, item.buffLen);
            // }                
            InsQueue(&(recvStObj->recvList), item);
            testIndex++;
        }
        usleep(1000);
    }

    fclose(file);
    printf("Finished reading file: %s\n", filename);
    return NULL;

}

int Testmain(int argc, char *argv[]) 
{
    printf("-------------------0306\n");

#if 0
    printf("TestAlsaMain\n");
    // Debug 
    TestAlsaMain(argc, argv);
    return 0;
#endif
    printf("Network Audio Recv\n");

    AudioRecvAllSt recvAllstObj;
    memset(&recvAllstObj, 0, sizeof(recvAllstObj));
    InitQueue(&(recvAllstObj.recvList));
    

    pthread_t recvThread;
    pthread_create(&recvThread, NULL, UdpRecvDataToBuff, (void *)&recvAllstObj);
    pthread_detach(recvThread);

    printf("Wait receive data...\n");
    while (IsQueueEmpty(&(recvAllstObj.recvList)))
    {
        usleep(1000); 
    }
    printf("Start play data...\n");

    // 播放音频
    PlayAudioFromRecvList(recvAllstObj);

    printf("-------------------0302\n");
    DestroyQueue(&(recvAllstObj.recvList));
    return 0;
}

// int main(int argc, char *argv[])
// {
//     printf("TestAlsaMain\n");
//     // Debug 
//     TestAlsaMain(argc, argv);
//     return 0;
// }